<!-- src/components/CommentSection.vue -->
<template>
  <div class="comment-section">
    <h4>评论区（{{ totalComments }}）</h4>

    <!-- 发主评论 -->
    <el-input
      v-model="newComment"
      type="textarea"
      :rows="3"
      placeholder="说点什么吧…"
      maxlength="200"
      show-word-limit
    />
    <el-button type="primary" size="small" @click="addComment" style="margin-top: 8px;">
      发送评论
    </el-button>

    <!-- 评论列表 -->
    <div v-if="totalComments === 0" class="empty">
      <p>暂无评论，快来抢沙发～</p>
    </div>

    <div v-else class="comments-list">
      <div
        v-for="comment in comments"
        :key="comment.id"
        class="comment-item"
      >
        <!-- 主评论 -->
        <el-avatar :size="28" :src="getAvatar()" />
        <div class="comment-content">
          <span class="comment-nickname">{{ comment.nickname }}</span>
          <span class="comment-text">{{ comment.text }}</span>
          <span class="comment-time">{{ formatTimeAgo(comment.time) }}</span>

          <!-- 回复按钮 -->
          <el-button
            size="small"
            type="info"
            link
            @click="startReply(comment.id)"
            style="font-size: 12px; margin-left: 8px;"
          >
            回复
          </el-button>

          <!-- 回复输入框（仅当点击“回复”时显示） -->
          <div v-if="showReplyInput && replyTo === comment.id" class="reply-input">
            <el-input
              v-model="replyText"
              type="textarea"
              :rows="2"
              placeholder="回复 @{{ comment.nickname }} ..."
              maxlength="100"
              show-word-limit
            />
            <div style="margin-top: 6px;">
              <el-button size="small" @click="submitReply(comment.id)">发送</el-button>
              <el-button size="small" @click="showReplyInput = false" type="info" link>取消</el-button>
            </div>
          </div>

          <!-- 二级评论列表 -->
          <div v-if="comment.replies.length > 0" class="replies-list">
            <div
              v-for="reply in comment.replies"
              :key="reply.id"
              class="reply-item"
            >
              <el-avatar :size="24" :src="getAvatar()" />
              <div class="reply-content">
                <span class="reply-nickname">{{ reply.nickname }}</span>
                <span class="reply-text">{{ reply.text }}</span>
                <span class="reply-time">{{ formatTimeAgo(reply.time) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<!-- src/components/CommentSection.vue -->
<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  postUsername: String
})

const emit = defineEmits(['comment-added'])

// 模拟当前用户
const username = props.postUsername || '游客'

// 新主评论
const newComment = ref('')

// 回复相关
const replyTo = ref(null)
const replyText = ref('')
const showReplyInput = ref(false)

// 评论数据（含 replies）
const comments = ref([
  {
    id: 1,
    nickname: '三坊七巷客',
    text: '同感！我也觉得闽江夜景最美',
    time: Date.now() - 3600000,
    replies: [
      {
        id: 101,
        nickname: '福州旅人',
        text: '是啊，灯光秀特别震撼！',
        time: Date.now() - 1800000
      }
    ]
  },
  {
    id: 2,
    nickname: '鼓山行者',
    text: '推荐白天去西禅寺，也很美。',
    time: Date.now() - 7200000,
    replies: []
  }
])

// 总评论数（主 + 子）
const totalComments = computed(() => {
  return comments.value.reduce((sum, c) => sum + 1 + c.replies.length, 0)
})

// 头像随机
const getAvatar = () => {
  const avatars = [
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c29f1a93c0ac8653.jpg',
    'https://cube.elemecdn.com/6/94/ae2e1b0fcb35bd936d75b56954eaf.jpeg',
    'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bc.png'
  ]
  return avatars[Math.floor(Math.random() * avatars.length)]
}

// 时间格式化
const formatTimeAgo = (timestamp) => {
  const now = Date.now()
  const diff = now - timestamp
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  return `${Math.floor(diff / day)}天前`
}

// 添加主评论
const addComment = () => {
  if (!newComment.value.trim()) return
  comments.value.unshift({
    id: Date.now(),
    nickname: username,
    text: newComment.value,
    time: Date.now(),
    replies: []
  })
  newComment.value = ''
  emit('comment-added')
}

// 回复功能
const startReply = (commentId) => {
  replyTo.value = commentId
  showReplyInput.value = true
  replyText.value = ''
}

const submitReply = (commentId) => {
  if (!replyText.value.trim()) return
  const comment = comments.value.find(c => c.id === commentId)
  if (comment) {
    comment.replies.unshift({
      id: Date.now(),
      nickname: username,
      text: replyText.value,
      time: Date.now()
    })
  }
  replyText.value = ''
  showReplyInput.value = false
  replyTo.value = null
  emit('comment-added')
}
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
  padding: 16px;
  border-top: 1px dashed #ddd;
}

.comment-item {
  display: flex;
  margin-top: 12px;
  align-items: flex-start;
}

.comment-content {
  margin-left: 10px;
  flex: 1;
}

.comment-nickname {
  font-weight: 600;
  color: #006666;
  font-size: 14px;
}

.comment-text {
  display: block;
  font-size: 14px;
  color: #333;
  margin: 4px 0;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.empty {
  text-align: center;
  color: #999;
  font-size: 13px;
  margin-top: 10px;
}

.replies-list {
  margin-top: 10px;
  padding-left: 38px; /* 与头像对齐 */
}

.reply-item {
  display: flex;
  margin-top: 8px;
  align-items: flex-start;
}

.reply-content {
  margin-left: 8px;
  flex: 1;
}

.reply-nickname {
  font-weight: 600;
  color: #006666;
  font-size: 13px;
}

.reply-text {
  display: block;
  font-size: 13px;
  color: #333;
  margin: 2px 0;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-input {
  margin-top: 8px;
  padding-left: 38px;
}

.reply-input .el-textarea {
  font-size: 13px;
}
</style>